﻿using ConfigInfoWebPlatform.API.BusinessCommon;
using ConfigInfoWebPlatform.API.DBCommon;
using ConfigInfoWebPlatform.API.HubMessage;
using ConfigInfoWebPlatform.API.ViewModel;
using ConfigInfoWebPlatform.Model;
using ConfigInfoWebPlatform.Model.Dtos.SelectDtos;
using ConfigInfoWebPlatform.Nlog;
using FileSecretAssemblyStandard;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Security.Claims;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace ConfigInfoWebPlatform.API.Controllers
{
    
    /// <summary>
    /// 
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class MainController : ControllerBase
    {
        readonly LogHelper _log;
        readonly string configRootPath;
        readonly InterfaceFileSecret FileSecret;
        readonly HubMessageServer hubMessageServer;
        /// <summary>
        /// 
        /// </summary>
        public MainController(LogHelper logHelper, IConfiguration configuration, InterfaceFileSecret fileSecret, HubMessageServer hubMessage)
        {
            _log = logHelper;
            configRootPath = configuration["AppSetting:configPath"].ToString();
            var dbpath = Path.Combine(configuration["AppSetting:dbpath"].ToString(), "DB/configPlatForm.db");
            var connstr = string.Format("Data Source={0}", $"{System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase}{dbpath}");
            _log.UpdateLogVar(new Dictionary<string, string>() { { "connectionString", connstr } });
            FileSecret = fileSecret;
            hubMessageServer = hubMessage;
        }

        /// <summary>
        /// 桌面概览
        /// </summary>
        /// <returns></returns>
        [HttpGet("welcome")]
        public JsonResult Welcome()
        {
            // 配置文件总列表
            ConfigFileList configFileList = new ConfigFileList();
            //SetConfig();
            //Statistic();
            //SetModuleConfigNote();
            configFileList = ParseCfgFile(string.Empty);
            var result = new
            {
                totalfilesnum = configFileList.TotalNum,
                processcfgfilesnum = configFileList.processCfgFilesNum,
                mlcfigfilenum = configFileList.MLCfigFileNum,
                modulecfgfilenum = configFileList.moduleCfgFileNum,
                todayaddfiles = configFileList.todayAddFiles
            };
            return new JsonResult(result);

        }

        /// <summary>
        /// 获取当前系统的所有菜单
        /// </summary>
        /// <returns></returns>
        [HttpGet("getmenus")]
        public JsonResult GetMenus()
        {
            List<MenusModel> menus = new List<MenusModel>();
            List<long> programNavicatIds = new List<long>();
            DAL_ProgramNavicat _programNavicat = new DAL_ProgramNavicat();
            UserInfoModel user = new UserInfoModel();
            var jsonStr = Base64Helper.DeCodeBase64(65001, Request.Headers["token"]);
            user = Newtonsoft.Json.JsonConvert.DeserializeObject<UserInfoModel>(jsonStr);
            DAL_UserInfo userDal = new DAL_UserInfo();
            string rid = userDal.GetUserRid(user.Id);
            List<ProgramNavicatModel> programNavicats = new List<ProgramNavicatModel>();
            menus = _programNavicat. GetProtramNavicatTree(user.Name,rid);
            return new JsonResult(menus);
        }


        /// <summary>
        /// 获取所有导航数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("getmenusnav")]
        public JsonResult GetMenusNav(int page, int limit)
        {
            var name = Request.Query["name"];
            var level = Request.Query["level"];
            List<ProgramNavicatModel> re = new List<ProgramNavicatModel>();
            DAL_ProgramNavicat _programNavicat = new DAL_ProgramNavicat();
            var programNavicats = _programNavicat.GetProgramNavicatInfos();
            if(!string.IsNullOrWhiteSpace(name))
            {
                programNavicats = programNavicats.Where(x => x.Name.Contains(name)).ToList();
            }

            if(!string.IsNullOrWhiteSpace(level))
            {
                int levelNum = Convert.ToInt32(level);
                programNavicats= programNavicats.Where(x => x.Level== levelNum).ToList();
            }

            if (programNavicats != null && programNavicats.Any())
            {
                re = programNavicats.Skip((page - 1) * limit).Take(limit).ToList();
            }
            return new JsonResult(new { code = 0, msg = "成功", count = programNavicats.Count, data = re });
        }

        /// <summary>
        /// 添加或者修改导航信息
        /// </summary>
        /// <returns></returns>
        [HttpPost("updatemenusnav")]
        public ActionResult UpdateMenusNav(ProgramNavicatModel model)
        {
            if (model != null)
            {
                if (!model.ParentId.HasValue)
                {
                    model.ParentId = 1000000000000000;
                }
                DAL_ProgramNavicat _programNavicat = new DAL_ProgramNavicat();
                var mo = _programNavicat.GetProgramNavicatInfoById(model.ID);
                string allParentId = string.Empty;
                var parentNav = _programNavicat.GetNavicatById(model.ParentId.Value);
                if (parentNav != null)
                {
                    if (!string.IsNullOrEmpty(parentNav.AllParentId))
                        allParentId = $"{parentNav.AllParentId},{parentNav.Id}";
                    else
                        allParentId = parentNav.Id.ToString();
                }
                model.AllParentId = allParentId;
                int result = 0;
                if (mo != null)
                {
                    //进行数据更新；
                    result = _programNavicat.UpdateNavicat(model);
                }
                else
                {
                    //进行数据插入；
                    result = _programNavicat.InsertNavicat(model);
                    if(Convert.ToInt64(model.ID)< 1002000000000000 && model.Level==3)
                    {
                        var fileName = $"{configRootPath}/config/wholeprocess.xml";
                        var wholeContent = System.IO.File.ReadAllText(fileName);
                        XDocument xdocument = XDocument.Parse(wholeContent);
                        XElement root = xdocument.Element("root");
                        string caseName = model.Name.Replace("流程", "");
                        string caseDir = model.Directory.Replace("\\","/");
                        string caseCode = Path.GetFileName(caseDir);
                        XElement caseTypeNode = new XElement("casetype");
                        caseTypeNode.SetAttributeValue("name", caseName);
                        caseTypeNode.SetAttributeValue("code", caseCode);
                        root.Add(caseTypeNode);
                        xdocument.Save(fileName);
                    }
                }
                if (result > 0)
                {
                    //添加信息到configFile表中
                    DAL_ConfigFile configFileDal = new DAL_ConfigFile();
                    Expression<Func<ConfigFiles, bool>> where = null;
                    where = where.And(x => x.Programid == model.ID);
                    where = where.And(x => x.Ctype == "D");
                    var fileInfo = configFileDal.GetSingleConfigByFilter(where);
                    string dirName = Path.GetFileNameWithoutExtension(model.Directory);
                    string parentPath = Path.GetDirectoryName(model.Directory);
                    if (!string.IsNullOrWhiteSpace(parentPath))
                        parentPath = parentPath.Replace("\\", "/");
                    if(fileInfo==null)
                    {
                        string currentId = System.Guid.NewGuid().ToString("N");
                        ConfigFileInfoModel configFileInfo = new ConfigFileInfoModel();
                        configFileInfo.currentId = currentId;
                        configFileInfo.name = dirName.ToLower();
                        configFileInfo.ctype = "D";
                        configFileInfo.path = model.Directory;
                        configFileInfo.parentPath = parentPath;
                        configFileInfo.fileSize = string.Empty;
                        configFileInfo.updateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        configFileInfo.createdTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); ;
                        configFileInfo.programId = model.ID;
                        configFileInfo.note = string.Empty;
                        string parentId = configFileDal.GetFileId(parentPath);
                        configFileInfo.parentId = parentId;
                        int parentLevel = configFileDal.GetFileLevel(parentPath);
                        configFileInfo.level = parentLevel + 1;
                        configFileInfo.status = "1";
                        configFileInfo.note = model.Note;
                        configFileDal.AddConfigFile(configFileInfo);
                    }
                    return Ok("数据更新成功！");
                }
            }
            return BadRequest("更新数据失败！");


        }

        /// <summary>
        /// 根据层级获取父级导航数据
        /// </summary>
        /// <param name="level"></param>
        /// <returns></returns>
        [HttpGet("getparentsbylevel")]
        public IActionResult GetParentsByLevel(int? level)
        {
            List<ProgramNavicatSelectDto> list = new List<ProgramNavicatSelectDto>();
            DAL_ProgramNavicat dal_programNavicat = new DAL_ProgramNavicat();
            if (level==1)
            {
                ProgramNavicatSelectDto nav = new ProgramNavicatSelectDto();
                nav.Id = 1000000000000000;
                nav.Name = "配置管理平台";
                list.Add(nav);
            }
            else
            {
                int upperLevel = level.Value - 1;
                list = dal_programNavicat.GetParentsByLevel(upperLevel);
            }
            return new JsonResult(new { 
                code=0,
                msg="成功",
                data=list
            });
        }

        /// <summary>
        /// 获取菜单的序号和编号
        /// </summary>
        [HttpGet("getnavid")]
        public IActionResult GetNavId(long parentId)
        {
            DAL_ProgramNavicat dal_programNavicat = new DAL_ProgramNavicat();
            ProgramNavicat lastNav = dal_programNavicat.GetLastNav(parentId);
            bool isParentNav = false;
            if (lastNav == null)
            {
                isParentNav = true;
                lastNav = dal_programNavicat.GetNavicatById(parentId);
            }
            long newId = 0;
            int newIndex = 0;
            if(lastNav!=null)
            {
                long oneStep = 1000000000000;
                long twoStep = 100000000;
                long treeStep = 10000;
                int level = lastNav.Level.Value;
                if (isParentNav)
                    level = lastNav.Level.Value + 1;
                switch (level)
                {
                    case 1:
                        newId = lastNav.Id + oneStep;
                        break;
                    case 2:
                        newId = lastNav.Id + twoStep;
                        break;
                    case 3:
                        newId = lastNav.Id + treeStep;
                        break;
                    case 4:
                        newId = lastNav.Id + 1;
                        break;
                }
                if (isParentNav)
                    newIndex += 1;
                else
                    newIndex = lastNav.Index.Value + 1;

            }
            return new JsonResult(new
            {
                code = 0,
                msg = "成功",
                data = new { id=newId,index=newIndex }
            });

        }

        [HttpGet("detail")]
        public IActionResult Detail(long id)
        {
            DAL_ProgramNavicat dal_programNavicat = new DAL_ProgramNavicat();
            var navInfo = dal_programNavicat.GetSingleNav(id);
            return new JsonResult(new { code = 0, msg = "成功", data = navInfo });
        }

        [HttpPost("updateconfigxpath")]
        public IActionResult UpdateConfigXpath()
        {
            int result = 0;
            string resultMsg = "更新完成";
            //获取用户信息
            UserInfoModel user = new UserInfoModel();
            var userJsonStr = Base64Helper.DeCodeBase64(65001, Request.Headers["user"]);
            user = Newtonsoft.Json.JsonConvert.DeserializeObject<UserInfoModel>(userJsonStr);
            //获取版本信息
            VersionModel version = new VersionModel();
            var versionJsonStr = Base64Helper.DeCodeBase64(65001, Request.Headers["version"]);
            version = Newtonsoft.Json.JsonConvert.DeserializeObject<VersionModel>(versionJsonStr);
            var versionPath = version?.Catalogue == "dev"
                                ? ""
                                : version?.Catalogue;
            string oldXpath = Request.Form["oldXpath"];
            string newXpath = Request.Form["newXpath"];
            List<string> updateErrFiles = new List<string>();
            List<ConfigFileInfoModel> CfgFileInfos = new List<ConfigFileInfoModel>();
            DAL_ConfigFile dal_configFile = new DAL_ConfigFile();
            CfgFileInfos = dal_configFile.GetConfigFileList();

            _log.WriteLog(LogHelper.logType.Info, $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}用户{user.Name}将包含xpath路径配置文件中路径{oldXpath}修改为{newXpath}");
            foreach (var item in CfgFileInfos)
            {
                string fileNameTemp = Path.Combine(configRootPath, versionPath, item.path).Replace("\\", "/");
                if (System.IO.File.Exists(fileNameTemp))
                {
                    try
                    {
                        string fileContent = FileSecret.DecryptFileToContent(fileNameTemp);
                        if (fileContent.IndexOf(oldXpath) > -1)
                        {
                            fileContent = fileContent.Replace(oldXpath, newXpath);
                            string encryptStr = FileSecret.EncryptContentToContent(fileContent);
                            System.IO.File.WriteAllText(fileNameTemp, fileContent);
                        }
                    }
                    catch (Exception ex)
                    {
                        updateErrFiles.Add(item.path);
                    }
                }
            }
            if (updateErrFiles.Any())
            {
                result=1;
                resultMsg= "未更新成功的文件有:" + string.Join(",", updateErrFiles);
            }
            return new JsonResult(new
            {
                code = result,
                msg=resultMsg
            });
        }


        private T RequestFormEntities<T>(IFormCollection form) where T : new()
        {
            T entity = Activator.CreateInstance<T>();
            PropertyInfo[] attrs = entity.GetType().GetProperties();
            foreach (PropertyInfo p in attrs)
            {
                var pro = form.Keys.FirstOrDefault(a => a.ToLower() == p.Name.ToLower());
                if (pro != null)
                {
                    try
                    {
                        Type type = p.PropertyType;
                        //判断type类型是否为泛型，因为nullable是泛型类
                        if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))//判断convertsionType是否为nullable泛型类  
                        {
                            //如果type为nullable类，声明一个NullableConverter类，该类提供从Nullable类到基础基元类型的转换  
                            System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(type);
                            //将type转换为nullable对的基础基元类型  
                            type = nullableConverter.UnderlyingType;
                        }
                        switch (type.Name)
                        {
                            case "String":
                                p.SetValue(entity, form[pro], null);
                                break;
                            default:
                                p.SetValue(entity, Convert.ChangeType(form[pro], type), null);
                                break;
                        }
                    }
                    catch (Exception e)
                    {
                        continue;
                    }
                }
                //foreach (string key in form.Keys)
                //{
                //    if (string.Compare(p.Name, key, true) == 0)
                //    {
                //        try
                //        {
                //            Type type = p.PropertyType;
                //            //判断type类型是否为泛型，因为nullable是泛型类
                //            if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))//判断convertsionType是否为nullable泛型类  
                //            {
                //                //如果type为nullable类，声明一个NullableConverter类，该类提供从Nullable类到基础基元类型的转换  
                //                System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(type);
                //                //将type转换为nullable对的基础基元类型  
                //                type = nullableConverter.UnderlyingType;
                //            }

                //            p.SetValue(entity, Convert.ChangeType(form[key], type), null);
                //        }
                //        catch (Exception e)
                //        {
                //            continue;
                //        }
                //    }
                //}
            }
            return entity;
        }

        /// <summary>
        /// 将配置文件的基本信息解析到ConfigFile的对象中
        /// **** 待研究改进:直接解析config下的整个目录结构，之后将level为1,2的放到菜单上显示，之后点击2级菜单传入目录的路径，再次解析
        ///      目录，这样写比较通用有目录调整时无需动代码，改后目录可以拆分开解析了两次，第一次只解析到
        /// ****
        /// </summary>
        /// <returns>配置文件基本信息</returns>
        private ConfigFileList ParseCfgFile(string model)
        {
            // 配置文件总列表
            ConfigFileList configFileList = new ConfigFileList();
            // 流程配置文件信息
            List<ConfigFileInfoModel> processCfgFileInfos = new List<ConfigFileInfoModel>();
            // 模块配置文件信息
            List<ConfigFileInfoModel> moduleCfgFileInfos = new List<ConfigFileInfoModel>();
            // 机器学习配置文件信息
            List<ConfigFileInfoModel> MLCfgFileInfos = new List<ConfigFileInfoModel>();
            // 案件信息要素中心配置
            List<ConfigFileInfoModel> caseElementCfgInfos = new List<ConfigFileInfoModel>();
            // 分析内部使用的配置文件(推导与优选配置文件)
            List<ConfigFileInfoModel> internalExeCfgInfos = new List<ConfigFileInfoModel>();

            // 从数据库中获取文件信息，不采用遍历路径
            DAL_ConfigFile configFileDal = new DAL_ConfigFile();
            // 遍历目录将文件信息填充到数据库中

            // 获取流程配置的文件结构
            int todayProcessFiles = 0;
            Expression<Func<ConfigFiles, bool>> where = null;
            if (string.IsNullOrEmpty(model) || model == "processConfig")
            {
                string processConfigPath = @"config/processconfig/analysisprocessconfig";
                _log.WriteLog(LogHelper.logType.Debug, "MainController-parseCfgFile方法获取流程配置文件的路径:" + processConfigPath);
                where = where.And(x => x.Path.StartsWith(processConfigPath) && x.Ctype == "F");
                processCfgFileInfos = configFileDal.GetConfigFilesByFilter(where);
                configFileList.processCfgFiles = processCfgFileInfos;
                if (processCfgFileInfos != null && processCfgFileInfos.Count > 0)
                {
                    configFileList.processCfgFilesNum = processCfgFileInfos.Count;
                    todayProcessFiles = processCfgFileInfos.Where(a => a.ctype == "F" && a.createdTime.Substring(0, 10) == DateTime.Now.ToString("yyyy-MM-dd")).ToList().Count();
                }
                else
                {
                    configFileList.processCfgFilesNum = 0;
                }
            }

            // 获取模块配置的文件结构
            int todayMoudleFiles = 0;
            if (string.IsNullOrEmpty(model) || model == "moduleConfig")
            {
                string moduleConfigPath = @"config/moduleconfig";
                _log.WriteLog(LogHelper.logType.Debug, "MainController-parseCfgFile方法获取模块配置文件的路径:" + moduleConfigPath);
                where = null;
                where = where.And(x => x.Path.StartsWith(moduleConfigPath) && x.Ctype == "F");
                moduleCfgFileInfos = configFileDal.GetConfigFilesByFilter(where);
                configFileList.moduleCfgFiles = moduleCfgFileInfos;
                if (moduleCfgFileInfos != null && moduleCfgFileInfos.Count > 0)
                {
                    configFileList.moduleCfgFileNum = moduleCfgFileInfos.Where(a => a.ctype == "F").ToList().Count;
                    todayMoudleFiles = moduleCfgFileInfos.Where(a => a.ctype == "F" && a.createdTime.Substring(0, 10) == DateTime.Now.ToString("yyyy-MM-dd")).ToList().Count();
                }
                else
                {
                    configFileList.moduleCfgFileNum = 0;
                    todayMoudleFiles = 0;
                }
            }

            // 获取机器学习配置的文件结构
            int todayMLFiles = 0;
            if (string.IsNullOrEmpty(model) || model == "MLConfig")
            {
                string MLConfigPath = @"config/mlconfig";
                _log.WriteLog(LogHelper.logType.Debug, "MainController-parseCfgFile方法获取机器学习配置文件的路径:" + MLConfigPath);
                where = null;
                where = where.And(x => x.Path.StartsWith(MLConfigPath) && x.Ctype == "F");
                MLCfgFileInfos = configFileDal.GetConfigFilesByFilter(where);
                configFileList.MLCfgFiles = MLCfgFileInfos;
                if (MLCfgFileInfos != null && MLCfgFileInfos.Count > 0)
                {
                    configFileList.MLCfigFileNum = MLCfgFileInfos.Count;
                    todayMLFiles = MLCfgFileInfos.Where(a => a.ctype == "F" && a.createdTime.Substring(0, 10) == DateTime.Now.ToString("yyyy-MM-dd")).ToList().Count();
                }
                else
                {
                    configFileList.MLCfigFileNum = 0;
                    todayMLFiles = 0;
                }
            }

            // 获取案件信息要素中心配置
            if (string.IsNullOrEmpty(model) || model == "elementNodesCode")
            {
                string caseElementConfigPath = @"config/elementnodescode";
                _log.WriteLog(LogHelper.logType.Debug, "MainController-parseCfgFile方法获取案件信息要素中心配置文件的路径:" + caseElementConfigPath);
                where = null;
                where = where.And(x => x.Path.StartsWith(caseElementConfigPath) && x.Ctype == "F");
                caseElementCfgInfos = configFileDal.GetConfigFilesByFilter(where);
                configFileList.caseElementCfgFiles = caseElementCfgInfos;
            }

            //// 获取分析程序内部执行使用到的配置文件
            //if (string.IsNullOrEmpty(model) || model == "optimizationCfg")
            //{
            //    string internalExeConfigPath = "config\\optimizationcfg";
            //    _log.WriteLog(LogHelper.logType.Debug, "MainController-parseCfgFile方法获取优选和推导配置文件的路径:" + internalExeConfigPath);
            //    // 从数据库中获取文件信息，不采用遍历路径
            //    internalExeCfgInfos = configFile.GetConfigFiles(internalExeConfigPath);

            //    configFileList.internalExeCfgFiles = internalExeCfgInfos;
            //}

            //获取所有文件；
            configFileList.TotalNum = configFileDal.GetConfigFilesWithOutDir().Count;

            //获取当天添加的数据
            configFileList.todayAddFiles = configFileDal.GetTodayConfigFiles().Count;
            return configFileList;
        }

        //刷新配置文件统计数量
        private void RefreshStatistics(string userName,string rid)
        {
            DAL_ConfigFile configFileDal = new DAL_ConfigFile();
            DAL_ProgramNavicat programNavicatDal = new DAL_ProgramNavicat();
            var configFileList = configFileDal.GetDeskStatistics();
            var desk = new
            {
                totalfilesnum = configFileList.TotalNum,
                processcfgfilesnum = configFileList.processCfgFilesNum,
                mlcfigfilenum = configFileList.MLCfigFileNum,
                modulecfgfilenum = configFileList.moduleCfgFileNum,
                todayaddfiles = configFileList.todayAddFiles
            };
            var navicats = programNavicatDal. GetProtramNavicatTree(userName,rid);
            var message = new { desk = desk, menus = navicats };
            hubMessageServer.SendMessage(JsonConvert.SerializeObject(message));
        }



        private void SetNavProcessSql()
        {
            string casefilepath = Path.Combine(System.Environment.CurrentDirectory, "CaseTypeList.json");
            string jsonStr = System.IO.File.ReadAllText(casefilepath);
            List<string> processSqls = new List<string>();

            // 获取json里面当前案件类型的文书列表
            Rootobject writList = System.Text.Json.JsonSerializer.Deserialize<Rootobject>(jsonStr);
            List<Casetype> casetypes = writList.casetypes;
            var optimizeFilePath = $"{configRootPath}/config/processconfig/optimizeprocessconfig";
            DirectoryInfo optfolder = new DirectoryInfo(optimizeFilePath);
            FileInfo[] optFiles = optfolder.GetFiles();
            long rootId = 1001000000000000;
            long oneStep = 1000000000000;
            long towStep = 100000000;
            long treeStep = 10000;
            List<string> optFileNames = new List<string>();
            List<string> groupCases = new List<string>();
            string beforeSql = "INSERT INTO main.ProgramNavicat(id, parentid, code, name, level, directory, navicatflag, img, href, index, note)";
            foreach (FileInfo opt in optFiles)
            {
                if (!opt.Extension.ToLower().Contains("back"))
                {
                    var fileName = Path.GetFileNameWithoutExtension(opt.FullName);
                    if (!string.IsNullOrWhiteSpace(fileName) && fileName != "index")
                    {
                        optFileNames.Add(fileName);
                        var ct = System.Text.RegularExpressions.Regex.Replace(fileName, "[0-9]", "", RegexOptions.IgnoreCase);
                        List<string> unl = new List<string> { "az", "bz","cz","dz", "ba","bb","bc","bd","be",};
                        if (!groupCases.Contains(ct) && !unl.Contains(ct))
                            groupCases.Add(ct);
                    }
                }
            }

            if(groupCases!=null && groupCases.Any())
            {
                var gcstart = rootId;
                int i = 0;
                foreach (var gc in groupCases.OrderBy(x=>x).ToList())
                {
                    StringBuilder gcSbl = new StringBuilder();
                    gcSbl.Append(beforeSql);
                    i += 1;
                    string gcName = string.Empty;
                    string gcNote = string.Empty;
                    string ctname = casetypes.FirstOrDefault(x => x.crcode == gc)?.ctname;
                    if (!string.IsNullOrWhiteSpace(ctname))
                    {
                        gcName = $"{ctname}流程";
                        gcNote= $"{ctname}流程配置";
                    }
                    ProgramNavicatModel gcnav = new ProgramNavicatModel();
                    gcstart += towStep;
                    gcnav.ID = gcstart;
                    gcnav.ParentId = rootId;
                    gcnav.Code = $"process_{gc}";
                    gcnav.Name = gcName;
                    gcnav.Level = 2;
                    gcnav.Directory = @$"config\processconfig\analysisprocessconfig\{gc}";
                    gcnav.NavicatFlag = 1;
                    gcnav.Img = "layui-icon layui-icon-file";
                    gcnav.Href = string.Empty;
                    gcnav.Index = i;
                    gcnav.Note = gcNote;
                    var endStr = $" VALUES({gcnav.ID}, {gcnav.ParentId}, '{gcnav.Code}', '{gcnav.Name}', {gcnav.Level}, '{gcnav.Directory}', {gcnav.NavicatFlag}, '{gcnav.Img}', '{gcnav.Href}', {gcnav.Index}, '{gcnav.Note}')";
                    gcSbl.Append(endStr);
                    List<string> childNames = optFileNames.Where(x => x.StartsWith(gc)).ToList();
                    processSqls.Add(gcSbl.ToString());
                    if (childNames!=null && childNames.Any())
                    {
                        var chStart = gcstart;
                        int j = 0;
                        foreach (var ch in childNames.OrderBy(x=>x).ToList())
                        {
                            StringBuilder chSbl = new StringBuilder();
                            chSbl.Append(beforeSql);
                            j += 1;
                            string chName = string.Empty;
                            string chNote = string.Empty;
                            string chctname = casetypes.FirstOrDefault(x => x.crcode == ch)?.ctname;
                            if (!string.IsNullOrWhiteSpace(chctname))
                            {
                                chName = $"{chctname}流程";
                                chNote = $"{chctname}流程配置";
                            }
                            ProgramNavicatModel chnav = new ProgramNavicatModel();
                            chStart += treeStep;
                            chnav.ID = chStart;
                            chnav.ParentId = gcnav.ID;
                            chnav.Code = $"process_{gc}_{ch}";
                            chnav.Name = chName;
                            chnav.Level = 3;
                            chnav.Directory = @$"config\processconfig\analysisprocessconfig\{gc}\{ch}";
                            chnav.NavicatFlag = 1;
                            chnav.Img = "layui-icon layui-icon-file";
                            chnav.Href = "processinfo/processindex.html?dir=";
                            chnav.Index = j;
                            chnav.Note = chNote;
                            string chendStr = $" VALUES({chnav.ID}, {chnav.ParentId}, '{chnav.Code}', '{chnav.Name}', {chnav.Level}, '{chnav.Directory}', {chnav.NavicatFlag}, '{chnav.Img}', '{chnav.Href}', {chnav.Index}, '{chnav.Note}')";
                            chSbl.Append(chendStr);
                            processSqls.Add(chSbl.ToString());
                        }
                    }
                }
            }
            var result = JsonConvert.SerializeObject(processSqls);
        }
        private void GetNavSql()
        {
            DAL_ProgramNavicat _programNavicat = new DAL_ProgramNavicat();
            List<ProgramNavicatModel> programNavicats = new List<ProgramNavicatModel>();
            programNavicats = _programNavicat.GetProgramNavicatInfos();
            List<ProgramNavicatModel> fristNavs = programNavicats.Where(x => x.Level == 3 && x.Code != "process").OrderBy(x=>x.Index).ToList();
            List<string> sqlList = new List<string>();
            List<string> configSqlList = new List<string>();
            long rootId = 1000000000000000;
            long oneStep = 1000000000000;
            long towStep = 100000000;
            long treeStep = 10000;
            long startId = 1001000000000000;
            int i = 1;
            var ConfigSqls = GetConfigSql(1, startId);
            if (ConfigSqls != null && ConfigSqls.Any())
            {
                sqlList.AddRange(ConfigSqls);
            }
            foreach (var frist in fristNavs)
            {
                i += 1;
                startId += oneStep;
                List<ProgramNavicatModel> towNavs = programNavicats.Where(x => x.ParentId == frist.ID).OrderBy(x => x.Index).ToList();
                if (towNavs != null && towNavs.Any())
                {
                    int j = 0;
                    long twoStartId = startId;
                    foreach (var two in towNavs)
                    {
                        j += 1;
                        twoStartId += towStep;
                        var twoConfigSqls = GetConfigSql(Convert.ToInt64(two.ID), twoStartId);
                        if(twoConfigSqls!=null && twoConfigSqls.Any())
                        {
                            sqlList.AddRange(twoConfigSqls);
                        }
                        string twoSql = $"UPDATE `main`.`ProgramNavicat` SET `id`={twoStartId} , `parentid` ={startId} , `index` = {j} WHERE `code` = '{two.Code}';";
                        sqlList.Add(twoSql);
                    }
                }
                var fristConfigSqls = GetConfigSql(Convert.ToInt64(frist.ID), startId);
                if (fristConfigSqls != null && fristConfigSqls.Any())
                {
                    sqlList.AddRange(fristConfigSqls);
                }
                string fristSql= $"UPDATE `main`.`ProgramNavicat` SET `id`={startId} , `parentid` ={rootId} , `index` = {i} WHERE `code` = '{frist.Code}';";
                sqlList.Add(fristSql);
            }
            var result= JsonConvert.SerializeObject(sqlList);
        }

        private List<string> GetConfigSql(long oldId,long newId)
        {
            List<string> result = new List<string>();
            List<ConfigFileInfoModel> configFileInfos = new List<ConfigFileInfoModel>();
            DAL_ConfigFile dAL_ConfigFile = new DAL_ConfigFile();
            configFileInfos = dAL_ConfigFile.GetConfigFiles(oldId);
            if (configFileInfos!=null && configFileInfos.Any())
            {
                foreach (var config in configFileInfos)
                {
                    string sql=$"UPDATE `main`.`ConfigFiles` SET `programid` = {newId} WHERE `currentid` = '{config.currentId}';";
                    result.Add(sql);
                }
            }
            return result;
        }

        private void SetAllParentId()
        {
            DAL_ProgramNavicat programNavicatDal = new DAL_ProgramNavicat();
            var oneNavs = programNavicatDal.GetNavicatByLevel(1);
            if (oneNavs != null && oneNavs.Any())
            {
                foreach (var item in oneNavs)
                {
                    ProgramNavicat parentNav = null;
                    if (item.ParentId.HasValue && item.ParentId!=0)
                        parentNav = programNavicatDal.GetNavicatById(item.ParentId.Value);
                    if (parentNav != null)
                    {
                        string allParentId = parentNav.Id.ToString();
                        programNavicatDal.UpdateNavicatAllParentId(item.Id, allParentId);
                        var childers = programNavicatDal.GetChildNavicat(item.Id);
                        if(childers!=null && childers.Any())
                        {
                            SetChildAllParentId(childers);
                        }
                    }
                }
            }
        }

        private void SetChildAllParentId(List<ProgramNavicat> navs)
        {
            DAL_ProgramNavicat programNavicatDal = new DAL_ProgramNavicat();
            if (navs != null && navs.Any())
            {
                foreach (var item in navs)
                {
                    ProgramNavicat parentNav = null;
                    if (item.ParentId.HasValue)
                        parentNav = programNavicatDal.GetNavicatById(item.ParentId.Value);
                    if (parentNav != null)
                    {
                        string allParentId = $"{parentNav.AllParentId},{parentNav.Id}";
                        programNavicatDal.UpdateNavicatAllParentId(item.Id, allParentId);
                        var childers = programNavicatDal.GetChildNavicat(item.Id);
                        if (childers != null && childers.Any())
                        {
                            SetChildAllParentId(childers);
                        }
                    }
                }
            }
        }

        private void SetConfigNavicatId()
        {
            DAL_ConfigFile configFileDal = new DAL_ConfigFile();
            DAL_ProgramNavicat navicatDal = new DAL_ProgramNavicat();
            var configList = configFileDal.GetNavidNoneConfigs();
            if (configList != null && configList.Any())
            {
                foreach (var config in configList)
                {
                    if (!string.IsNullOrWhiteSpace(config.ParentPath))
                    {
                        var nav = navicatDal.GetNavicatByDirPath(config.ParentPath);
                        if (nav != null)
                        {
                            configFileDal.UpdateConfigProgramid(config.Currentid, nav.Id);
                        }

                    }
                }
            }
        }

        #region 整理配置信息数据，将各模块下目录及文件信息插入到ConfigFiles表中
        private void SetConfig()
        {
            SetRootConfig();
            SetProcessConfig();
            SetModuleConfig();
            SetRefineConfig();
            SetNodeConfig();
            SetMachineConfig();
            SetStructConfig();
        }

        /// <summary>
        /// 根节点配置
        /// </summary>
        private void SetRootConfig()
        {
            DAL_ProgramNavicat programNavicatDal = new DAL_ProgramNavicat();
            DAL_ConfigFile configFileDal = new DAL_ConfigFile();
            var rootNav = programNavicatDal.GetNavicatByDirPath(@"config");
            ConfigFiles rootConfig = new ConfigFiles();
            rootConfig.Currentid = "2bb03cbdb81c451cb15acf944954daa4";
            rootConfig.Parentid = "";
            rootConfig.Level = 1;
            rootConfig.Name = "config";
            rootConfig.Ctype = "D";
            rootConfig.Path = $"config";
            rootConfig.ParentPath = "";
            rootConfig.Updatetime = "2020-01-01 01:00:00";
            rootConfig.Createdtime = "2020-01-01 01:00:00";
            rootConfig.Programid = rootNav.Id;
            rootConfig.Status = "1";
            rootConfig.Note = "配置管理平台根节点";
            configFileDal.InsertConfig(rootConfig);
        }

        /// <summary>
        /// 整理分析流程配置信息
        /// </summary>
        private void SetProcessConfig()
        {
            DAL_ProgramNavicat programNavicatDal = new DAL_ProgramNavicat();
            DAL_ConfigFile configFileDal = new DAL_ConfigFile();
            var processNav = programNavicatDal.GetNavicatByDirPath(@"config/processconfig/analysisprocessconfig");
            if (processNav != null)
            {
                var processPath = processNav.Directory;
                configFileDal.DeleteConfigFileLike(processPath);
                var processConfig = configFileDal.GetConfigFileByPath(processPath);
                if (processConfig == null)
                {
                    processConfig = new ConfigFiles();
                    processConfig.Currentid = System.Guid.NewGuid().ToString("N");
                    processConfig.Parentid = "2bb03cbdb81c451cb15acf944954daa4";
                    processConfig.Level = 1;
                    processConfig.Name = Path.GetFileName(processPath).ToLower();
                    processConfig.Ctype = "D";
                    processConfig.Path = processPath;
                    processConfig.ParentPath = Path.GetDirectoryName(processPath).Replace("\\", @"/").ToLower();
                    processConfig.Updatetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    processConfig.Createdtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    processConfig.Programid = processNav.Id;
                    processConfig.Status = "1";
                    processConfig.Note = "分析流程";
                    configFileDal.InsertConfig(processConfig);
                }
                var casefullNavs = programNavicatDal.GetChildNavicat(processNav.Id);
                if (casefullNavs != null && casefullNavs.Any())
                {
                    foreach (var casefull in casefullNavs)
                    {
                        if (casefull.IsDirectory != 1)
                        {
                            var caseNavs = programNavicatDal.GetChildNavicat(casefull.Id);
                            foreach (var caseNav in caseNavs)
                            {
                                string filepath = Path.Combine(System.Environment.CurrentDirectory, "CaseTypeWrit.json");
                                string jsonStr = System.IO.File.ReadAllText(filepath);
                                // 获取json里面当前案件类型的文书列表
                                List<WritsItem> writTypes = new List<WritsItem>();
                                WRoot writList = System.Text.Json.JsonSerializer.Deserialize<WRoot>(jsonStr);
                               
                                var casePath = caseNav.Directory;
                                var caseTypeCode = Path.GetFileNameWithoutExtension(casePath);
                                var caseConfig = configFileDal.GetConfigFileByPath(casePath);
                                var caseWir = writList.CaseTypeWrit.Where(x => x.code == caseTypeCode).FirstOrDefault();
                                if (caseConfig == null)
                                {
                                    caseConfig = new ConfigFiles();
                                    caseConfig.Currentid = System.Guid.NewGuid().ToString("N");
                                    caseConfig.Parentid = processConfig.Currentid;
                                    caseConfig.Level = 2;
                                    caseConfig.Name = Path.GetFileName(casePath).ToLower();
                                    caseConfig.Ctype = "D";
                                    caseConfig.Path = casePath;
                                    caseConfig.ParentPath = Path.GetDirectoryName(casePath).Replace("\\", @"/").ToLower();
                                    caseConfig.Updatetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                    caseConfig.Createdtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                    caseConfig.Programid = caseNav.Id;
                                    caseConfig.Status = "1";
                                    caseConfig.Note = "";
                                    configFileDal.InsertConfig(caseConfig);
                                }
                                
                                DirectoryInfo directory = new DirectoryInfo(Path.Combine(configRootPath, casePath));

                                DirectoryInfo[] childDir = directory.GetDirectories();
                                //数据源
                                foreach (DirectoryInfo directoryInfo in childDir)
                                {
                                    var docWir = caseWir?.writs.Where(x => x.code == directoryInfo.Name.ToLower()).FirstOrDefault();
                                    ConfigFiles sourceConfig = new ConfigFiles();
                                    sourceConfig.Currentid = System.Guid.NewGuid().ToString("N");
                                    sourceConfig.Parentid = caseConfig.Currentid;
                                    sourceConfig.Level = 3;
                                    sourceConfig.Name = directoryInfo.Name.ToLower();
                                    sourceConfig.Ctype = "D";
                                    sourceConfig.Path = $"{casePath}/{directoryInfo.Name.ToLower()}";
                                    sourceConfig.ParentPath = casePath;
                                    sourceConfig.Updatetime = directoryInfo.LastAccessTime.ToString("yyyy-MM-dd HH:mm:ss");
                                    sourceConfig.Createdtime = directoryInfo.CreationTime.ToString("yyyy-MM-dd HH:mm:ss");
                                    sourceConfig.Programid = caseNav.Id;
                                    sourceConfig.Status = "1";
                                    sourceConfig.Note = docWir?.name.ToLower().Replace($"-{docWir?.code}", "");
                                    configFileDal.InsertConfig(sourceConfig);
                                    FileInfo[] files = directoryInfo.GetFiles();
                                    if (files != null && files.Length > 0)
                                    {
                                        foreach (FileInfo file in files)
                                        {
                                            if (file.Extension == ".xml" || file.Extension == ".txt" || file.Extension == ".json")
                                            {
                                                ConfigFiles configFileInfo = new ConfigFiles();
                                                configFileInfo.Programid = caseNav.Id;
                                                configFileInfo.Currentid = System.Guid.NewGuid().ToString("N");
                                                configFileInfo.Parentid = sourceConfig.Currentid;
                                                configFileInfo.Level = 4;
                                                configFileInfo.Name = file.Name;
                                                configFileInfo.Ctype = "F";
                                                configFileInfo.Path = $"{sourceConfig.Path}/{file.Name}";
                                                configFileInfo.ParentPath = sourceConfig.Path;
                                                configFileInfo.Filesize = file.Length.ToString() + "B";
                                                configFileInfo.Updatetime = file.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
                                                configFileInfo.Createdtime = file.CreationTime.ToString("yyyy-MM-dd HH:mm:ss");
                                                configFileDal.InsertConfig(configFileInfo);
                                            }
                                        }

                                    }

                                }
                            }
                        }
                    }

                }
            }
        }

        /// <summary>
        /// 整理模块配置信息
        /// </summary>
        private void SetModuleConfig()
        {
            //config/moduleconfig
            DAL_ProgramNavicat programNavicatDal = new DAL_ProgramNavicat();
            DAL_ConfigFile configFileDal = new DAL_ConfigFile();
            configFileDal.DeleteConfigFileLike(@"config/moduleconfig");
            Expression<Func<ProgramNavicat, bool>> navWhere = null;
            navWhere = navWhere.And(x => x.Directory.Contains(@"config/moduleconfig") && x.Level == 1);
            var navs = programNavicatDal.GetNavicatByFilter(navWhere);
            if (navs != null && navs.Any())
            {
                foreach (var moduleNav in navs)
                {
                    if (moduleNav != null)
                    {
                        var modulePath = moduleNav.Directory;
                        var moduleConfig = configFileDal.GetConfigFileByPath(modulePath);
                        if (moduleConfig == null)
                        {
                            moduleConfig = new ConfigFiles();
                            moduleConfig.Currentid = System.Guid.NewGuid().ToString("N");
                            moduleConfig.Parentid = "2bb03cbdb81c451cb15acf944954daa4";
                            moduleConfig.Level = 1;
                            moduleConfig.Name = Path.GetFileName(modulePath).ToLower();
                            moduleConfig.Ctype = "D";
                            moduleConfig.Path = modulePath;
                            moduleConfig.ParentPath = Path.GetDirectoryName(modulePath).Replace("\\", @"/").ToLower();
                            moduleConfig.Updatetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                            moduleConfig.Createdtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                            moduleConfig.Programid = moduleNav.Id;
                            moduleConfig.Status = "1";
                            moduleConfig.Note = moduleNav.Name.Replace("配置", "");
                            configFileDal.InsertConfig(moduleConfig);
                            SetChilderConfig(modulePath, moduleConfig.Currentid, moduleNav.Id, moduleConfig.Level.Value);
                        }
                    }
                }
            }

        }

        /// <summary>
        /// 调整精细化配置信息
        /// </summary>
        private void SetRefineConfig()
        {
            DAL_ProgramNavicat programNavicatDal = new DAL_ProgramNavicat();
            DAL_ConfigFile configFileDal = new DAL_ConfigFile();
            configFileDal.DeleteConfigFileLike(@"config/detailingcfg");
            var refineNav = programNavicatDal.GetNavicatByDirPath(@"config/detailingcfg");
            if (refineNav != null)
            {
                var refinePath = refineNav.Directory;
                var refineConfig = configFileDal.GetConfigFileByPath(refinePath);
                if (refineConfig == null)
                {
                    refineConfig = new ConfigFiles();
                    refineConfig.Currentid = System.Guid.NewGuid().ToString("N");
                    refineConfig.Parentid = "2bb03cbdb81c451cb15acf944954daa4";
                    refineConfig.Level = 1;
                    refineConfig.Name = Path.GetFileName(refinePath).ToLower();
                    refineConfig.Ctype = "D";
                    refineConfig.Path = refinePath;
                    refineConfig.ParentPath = Path.GetDirectoryName(refinePath).Replace("\\", @"/").ToLower();
                    refineConfig.Updatetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    refineConfig.Createdtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    refineConfig.Programid = refineNav.Id;
                    refineConfig.Status = "1";
                    refineConfig.Note = "精细化配置";
                    configFileDal.InsertConfig(refineConfig);
                    SetChilderConfig(refinePath, refineConfig.Currentid, refineNav.Id, refineConfig.Level.Value);
                }
            }
        }

        /// <summary>
        /// 调整要素节点编号信息
        /// </summary>
        private void SetNodeConfig()
        {
            DAL_ProgramNavicat programNavicatDal = new DAL_ProgramNavicat();
            DAL_ConfigFile configFileDal = new DAL_ConfigFile();
            configFileDal.DeleteConfigFileLike(@"config/elementnodescode");
            var nodeNav = programNavicatDal.GetNavicatByDirPath(@"config/elementnodescode");
            if (nodeNav != null)
            {
                var nodePath = nodeNav.Directory;
                var nodeConfig = configFileDal.GetConfigFileByPath(nodePath);
                if (nodeConfig == null)
                {
                    nodeConfig = new ConfigFiles();
                    nodeConfig.Currentid = System.Guid.NewGuid().ToString("N");
                    nodeConfig.Parentid = "2bb03cbdb81c451cb15acf944954daa4";
                    nodeConfig.Level = 1;
                    nodeConfig.Name = Path.GetFileName(nodePath).ToLower();
                    nodeConfig.Ctype = "D";
                    nodeConfig.Path = nodePath;
                    nodeConfig.ParentPath = Path.GetDirectoryName(nodePath).Replace("\\", @"/").ToLower();
                    nodeConfig.Updatetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    nodeConfig.Createdtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    nodeConfig.Programid = nodeNav.Id;
                    nodeConfig.Status = "1";
                    nodeConfig.Note = "要素节点编号";
                    configFileDal.InsertConfig(nodeConfig);
                    SetChilderConfig(nodePath, nodeConfig.Currentid, nodeNav.Id, nodeConfig.Level.Value);
                }
            }
        }

        /// <summary>
        /// 调整机器学习配置信息
        /// </summary>
        private void SetMachineConfig()
        {
            DAL_ProgramNavicat programNavicatDal = new DAL_ProgramNavicat();
            DAL_ConfigFile configFileDal = new DAL_ConfigFile();
            configFileDal.DeleteConfigFileLike(@"config/mlconfig");
            var machineNav = programNavicatDal.GetNavicatByDirPath(@"config/mlconfig");
            if (machineNav != null)
            {
                var machinePath = machineNav.Directory;
                var machineConfig = configFileDal.GetConfigFileByPath(machinePath);
                if (machineConfig == null)
                {
                    machineConfig = new ConfigFiles();
                    machineConfig.Currentid = System.Guid.NewGuid().ToString("N");
                    machineConfig.Parentid = "2bb03cbdb81c451cb15acf944954daa4";
                    machineConfig.Level = 1;
                    machineConfig.Name = Path.GetFileName(machinePath).ToLower();
                    machineConfig.Ctype = "D";
                    machineConfig.Path = machinePath;
                    machineConfig.ParentPath = Path.GetDirectoryName(machinePath).Replace("\\", @"/").ToLower();
                    machineConfig.Updatetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    machineConfig.Createdtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    machineConfig.Programid = machineNav.Id;
                    machineConfig.Status = "1";
                    machineConfig.Note = "机器学习";
                    configFileDal.InsertConfig(machineConfig);
                    SetChilderConfig(machinePath, machineConfig.Currentid, machineNav.Id, machineConfig.Level.Value);
                }
            }
        }

        /// <summary>
        /// 调整要素结构配置信息
        /// </summary>
        private void SetStructConfig()
        {
            DAL_ProgramNavicat programNavicatDal = new DAL_ProgramNavicat();
            DAL_ConfigFile configFileDal = new DAL_ConfigFile();
            configFileDal.DeleteConfigFileLike(@"config/casetypestructconfig");
            var structNav = programNavicatDal.GetNavicatByDirPath(@"config/casetypestructconfig");
            if (structNav != null)
            {
                var structPath = structNav.Directory;
                var structConfig = configFileDal.GetConfigFileByPath(structPath);
                if (structConfig == null)
                {
                    structConfig = new ConfigFiles();
                    structConfig.Currentid = System.Guid.NewGuid().ToString("N");
                    structConfig.Parentid = "2bb03cbdb81c451cb15acf944954daa4";
                    structConfig.Level = 1;
                    structConfig.Name = Path.GetFileName(structPath).ToLower();
                    structConfig.Ctype = "D";
                    structConfig.Path = structPath;
                    structConfig.ParentPath = Path.GetDirectoryName(structPath).Replace("\\", @"/").ToLower();
                    structConfig.Updatetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    structConfig.Createdtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    structConfig.Programid = structNav.Id;
                    structConfig.Status = "1";
                    structConfig.Note = "案件要素中心结构";
                    configFileDal.InsertConfig(structConfig);
                    SetChilderConfig(structPath, structConfig.Currentid, structNav.Id, structConfig.Level.Value);
                }
            }
        }

        private void SetChilderConfig(string dirPath, string parentId, long programid, int level)
        {
            DirectoryInfo directory = new DirectoryInfo(Path.Combine(configRootPath, dirPath));

            DirectoryInfo[] childDir = directory.GetDirectories();

            DAL_ConfigFile configFileDal = new DAL_ConfigFile();
            DAL_ProgramNavicat navicatDal = new DAL_ProgramNavicat();
            //子级目录
            foreach (DirectoryInfo directoryInfo in childDir)
            {
                long navId = programid;
                var navinfo = navicatDal.GetNavicatByDirPath($"{dirPath}/{directoryInfo.Name.ToLower()}");
                if(navinfo!=null && navinfo.Id>0)
                {
                    navId = navinfo.Id;
                }
                ConfigFiles sourceConfig = new ConfigFiles();
                sourceConfig.Currentid = System.Guid.NewGuid().ToString("N");
                sourceConfig.Parentid = parentId;
                sourceConfig.Level = level + 1;
                sourceConfig.Name = directoryInfo.Name.ToLower();
                sourceConfig.Ctype = "D";
                sourceConfig.Path = $"{dirPath}/{directoryInfo.Name.ToLower()}";
                sourceConfig.ParentPath = dirPath;
                sourceConfig.Updatetime = directoryInfo.LastAccessTime.ToString("yyyy-MM-dd HH:mm:ss");
                sourceConfig.Createdtime = directoryInfo.CreationTime.ToString("yyyy-MM-dd HH:mm:ss");
                sourceConfig.Programid = navId;
                sourceConfig.Status = "1";
                sourceConfig.Note = "";
                configFileDal.InsertConfig(sourceConfig);
                FileInfo[] files = directoryInfo.GetFiles();
                if (files != null && files.Length > 0)
                {
                    foreach (FileInfo file in files)
                    {
                        if (file.Extension == ".xml" || file.Extension == ".txt" || file.Extension == ".json")
                        {
                            ConfigFiles configFileInfo = new ConfigFiles();
                            configFileInfo.Programid = navId;
                            configFileInfo.Currentid = System.Guid.NewGuid().ToString("N");
                            configFileInfo.Parentid = sourceConfig.Currentid;
                            configFileInfo.Level = 4;
                            configFileInfo.Name = file.Name;
                            configFileInfo.Ctype = "F";
                            configFileInfo.Path = $"{sourceConfig.Path}/{file.Name}";
                            configFileInfo.ParentPath = sourceConfig.Path;
                            configFileInfo.Filesize = file.Length.ToString() + "B";
                            configFileInfo.Updatetime = file.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
                            configFileInfo.Createdtime = file.CreationTime.ToString("yyyy-MM-dd HH:mm:ss");
                            configFileDal.InsertConfig(configFileInfo);
                        }
                    }

                }

                DirectoryInfo[] childFolders = directoryInfo.GetDirectories();
                if (childFolders != null && childFolders.Length > 0)
                {
                    SetChilderConfig(sourceConfig.Path, sourceConfig.Currentid, navId, sourceConfig.Level.Value);
                }
            }
        }
        #endregion

        #region 修改模块配置文件信息备注(不包含公共配置文件)
        private void SetModuleConfigNote()
        {
            DAL_ConfigFile configFileDal = new DAL_ConfigFile();
            Expression<Func<ConfigFiles, bool>> configFileWhere = null;
            configFileWhere.And(x => x.Path.Contains(@"config/moduleconfig") && x.Ctype == "F" && !x.ParentPath.Contains(@"config/moduleconfig/commonconfig"));
            var moduleConfigs = configFileDal.GetConfigFilesByFilter(configFileWhere);
            if(moduleConfigs!=null && moduleConfigs.Any())
            {
                foreach (var config in moduleConfigs)
                {
                    var fileFullPath = $"{configRootPath}/{config.path}";
                    if(System.IO.File.Exists(fileFullPath))
                    {
                        string xmlContent = FileSecret.DecryptFileToContent(fileFullPath);
                        if(!string.IsNullOrWhiteSpace(xmlContent))
                        {
                            XDocument xdocument = XDocument.Parse(xmlContent);
                            var rootNode = xdocument.Element("root");
                            if(rootNode!=null)
                            {
                                var noteAttr = rootNode.Attribute("explain");
                                var noteValue = noteAttr?.Value;
                                if(!string.IsNullOrWhiteSpace(noteValue))
                                {
                                    configFileDal.UpdateConfigFileNote(config.currentId, noteValue);
                                }
                            }
                        }
                    }
                    
                }
            }
        }
        
        #endregion


        #region 统计各菜单下文件夹及文件数量
        private void Statistic()
        {
            DAL_ProgramNavicat programNavicatDal = new DAL_ProgramNavicat();
            DAL_ConfigFile configFileDal = new DAL_ConfigFile();
            DAL_MenuStatistics statisticsDal = new DAL_MenuStatistics();
            Expression<Func<ProgramNavicat, bool>> navWhere = null;
            navWhere = navWhere.And(x => x.IsStatistics == 1);
            var navs = programNavicatDal.GetNavicatByFilter(navWhere);
            Expression<Func<ConfigFiles, bool>> configWhere = null;
            Expression<Func<MenuStatistics, bool>> statisticsWhere = null;
            if (navs!=null && navs.Any())
            {
                var maxLevel = navs.Max(x => x.Level);
                for (int i = maxLevel.Value; i > 0; i--)
                {
                    var navList = navs.Where(x => x.Level == i).ToList();
                    if (navList != null && navList.Any()) {

                        foreach (var nav in navList)
                        {
                            var floderNum = 0;
                            var fileNum = 0;
                            if (nav.IsDirectory==1)
                            {
                                configWhere = null;
                                configWhere = configWhere.And(x => x.Path.Contains($"{nav.Directory}/"));
                                var configs = configFileDal.GetConfigFilesByFilter(configWhere);
                                floderNum = configs.Where(x=>x.ctype=="D").Count();
                                fileNum = configs.Where(x => x.ctype == "F").Count();
                            }
                            else if(nav.IsDirectory==0 || nav.IsDirectory==null)
                            {
                                var childerIds = navs.Where(x => x.ParentId == nav.Id).Select(x => x.Id).ToList();
                                statisticsWhere = null;
                                statisticsWhere = statisticsWhere.And(x => childerIds.Contains(x.NavicatId));
                                var statisticsList = statisticsDal.GetMenuStatisticsByFilter(statisticsWhere);
                                if(statisticsList!=null && statisticsList.Any())
                                {
                                    floderNum = statisticsList.Sum(x => x.FloderNumber).GetValueOrDefault();
                                    fileNum = statisticsList.Sum(x => x.FileNumber).GetValueOrDefault();
                                }
                            }

                            MenuStatistics statistics = statisticsDal.GetStatisticsByNavId(nav.Id);
                            if(statistics==null)
                            {
                                statistics = new MenuStatistics();
                                statistics.Id = System.Guid.NewGuid().ToString("N");
                                statistics.NavicatId = nav.Id;
                                statistics.FloderNumber = floderNum;
                                statistics.FileNumber = fileNum;
                                statisticsDal.InsertsMenuStatistics(statistics);
                            }
                        }
                    }
                }
            }
        }
        #endregion
    }

    public class Rootobject
    {
        public List<Casetype> casetypes { get; set; }
    }

    public class Casetype
    {
        public string ctname { get; set; }
        public string crcode { get; set; }
    }






}
